$.getScript("http://localhost:8080/fitso/ajax/engine.js");
$.getScript("http://localhost:8080/fitso/ajax/interface/userservice.js");

// initialize everything
$(function() {
	// setup the registration dialog
	$("#register-dialog").dialog( {
		bgiframe : true,
		autoOpen : false,
		height : 300,
		width: 400,
		modal : true,
		buttons : {
			'Register' : function() {
				var user = new User();
				user.email = $('#register-email').val();
				user.password = $('#register-password').val();
				user.firstName = $('#register-first-name').val();
				user.lastName = $('#register-last-name').val();
				register(user);
				$('#register-dialog').dialog('close');
			}
		}
	});

	// setup the login event
	$('#login-button').click(function(e) {
		login($('#login-email').val(), $('#login-password').val());	
	});

	// open the login dialog
	$("#register-new-user").click(function(e) {
		$('#register-dialog').dialog('open')
	});
});

function register(user) {
	userservice.register(user, {
		callback : function() {
			alert('you have been registerd');
			login(user.email, user.password);
		},
		errorHandler : function() {
			alert('something wrong');
		}
	});
}

function login(email, password) {
	// login with the user service
	return userservice.login(email, password, {
		callback : function(user) {
			$('#signon-header').html('Welcome ' + user.firstName);
			$('#signon-box').html('You lucky dog, you\'re using Fitso');
		},
		errorHandler : function(msg) {
			alert("login error");
		}
	});
}